package cmd

import (
	"github.com/spf13/cobra"
	"io"
	"net/http"
	"os"
	"strings"
)

func init() {
	clashCmd.PersistentFlags().StringVarP(&proxyFile, "proxy", "p", "./clash.yaml", "clash file path")
	rootCmd.AddCommand(clashCmd)
}

var clashCmd = &cobra.Command{
	Use:   "clash",
	Short: "This clash command",
	Long:  "This clash command",

	Run: func(cmd *cobra.Command, args []string) {
		for _, clash := range Cfg.Clash {
			doRun(clash.Url, clash.Path)
		}
	},
}

func doRun(url, path string) {
	// 创建HTTP客户端
	client := &http.Client{}

	// 创建HTTP请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		Log.Errorln("Error creating request:", err)
		return
	}

	// 设置请求头（如果需要）
	req.Header.Set("Content-Type", "application/json")

	// 发送请求并获取响应
	resp, err := client.Do(req)
	if err != nil {
		Log.Errorln("Error making request:", err)
		return
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		Log.Errorln("Error: received non-200 response code:", resp.StatusCode)
		return
	}

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		Log.Errorln("Error reading response body:", err)
		return
	}

	if strings.HasPrefix(path, "./") {
		path = strings.Replace(path, "./", runDir+"/", 1)
	}

	err = os.WriteFile(path, body, 0777)
	if err != nil {
		Log.Errorln("Error Writing File:", err)
		return
	}

	Log.WithField("path", path).Info("Write Success")
}
